package global

import (
	"github.com/sirupsen/logrus"
	"hcy-api/lib/db"
	"hcy-api/structs/tables"
	"vap/daemon/gua"
)

func InitDB() {
	var err error
	DB, err = db.GetDB(Conf.DB.Supper, Conf.DB.ShowSqlLog, Conf.DB.Source, Conf.AppFolder)
	if err != nil {
		logrus.Panicf("连接数据库失败：%v", err)
	}
	autoMigrate()
}

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		&tables.VapHost{},
		&tables.VapCluster{},
		&tables.VapSession{},
		&tables.VapGuacd{},
		&tables.VapAppInstall{},
		&tables.VapAppIssue{},
		&tables.MapHostSessionForApp{},
		&tables.GuaProperty{},
		&tables.VapSettings{},
		&tables.VapShHost{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				logrus.Errorf("初始化数据库表结构异常: %v", err)
			}
		}
	}

	initGuaProperties()
}

func initGuaProperties() {
	var dli []tables.GuaProperty
	err := DB.Model(&tables.GuaProperty{}).Where("id in ?", []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Find(&dli).Error
	if err != nil {
		logrus.Errorf("load gua properties err: %v", err)
		return
	}
	var mpro = make(map[int64]tables.GuaProperty, 0)
	for _, item := range dli {
		mpro[item.Id] = item
	}
	p1 := tables.GuaProperty{Id: 1, Scope: tables.ScopeForGlobal, Key: gua.Domain, Value: ""}
	p2 := tables.GuaProperty{Id: 2, Scope: tables.ScopeForGlobal, Key: gua.Security, Value: "any"}
	p3 := tables.GuaProperty{Id: 3, Scope: tables.ScopeForGlobal, Key: gua.IgnoreCert, Value: "true"}
	p4 := tables.GuaProperty{Id: 4, Scope: tables.ScopeForGlobal, Key: gua.ResizeMethod, Value: "reconnect"}
	p5 := tables.GuaProperty{Id: 5, Scope: tables.ScopeForGlobal, Key: gua.DisableAudio, Value: "false"}
	p6 := tables.GuaProperty{Id: 6, Scope: tables.ScopeForGlobal, Key: gua.EnableAudioInput, Value: "false"}
	p7 := tables.GuaProperty{Id: 7, Scope: tables.ScopeForGlobal, Key: gua.RecordingPath, Value: ""}
	p8 := tables.GuaProperty{Id: 8, Scope: tables.ScopeForGlobal, Key: gua.CreateRecordingPath, Value: "true"}
	p9 := tables.GuaProperty{Id: 9, Scope: tables.ScopeForGlobal, Key: gua.EnableTouch, Value: "false"}
	p10 := tables.GuaProperty{Id: 10, Scope: tables.ScopeForGlobal, Key: gua.ForceLossless, Value: "false"}
	li := []tables.GuaProperty{p1, p2, p3, p4, p5, p6, p7, p8, p9, p10}
	for _, item := range li {
		if _, ok := mpro[item.Id]; !ok {
			if DB.Create(&item).Error != nil {
				logrus.Errorf("create gua properties err: %v", err)
				return
			}
		}
	}
}
